//
//  HTTPhelper.m
//  cookBook
//
//  Created by xalo on 16/1/23.
//  Copyright © 2016年 张广斌. All rights reserved.
//

#import "HTTPhelper.h"
#import "Model.h"
#import <AFHTTPSessionManager.h>// 导入AFHTTPSessionManager框架
@interface HTTPhelper ()
@property (nonatomic,strong) NSMutableArray *cookListArray;// 用来存储model信息的数组

@end

static HTTPhelper *handle = nil;
@implementation HTTPhelper

// 单例
+(HTTPhelper *)sharedManeger
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[HTTPhelper alloc] init];
    });
    return handle;
}



// 请求网络数据
- (void)fecthCookListGetingSession:(Block)block url:(NSString *)url
{
    // 创建manager对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    
    // 执行数据请求方法
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        __weak HTTPhelper *weakSelf = self;
        
        // 请求数据
        NSArray *array = responseObject[@"results"];
        
        // 遍历数组
        for (NSDictionary *dic in array) {
            
            // 创建model对象存储数据
            Model *model = [[Model alloc] init];
            
            // kvc赋值
            [model setValuesForKeysWithDictionary:dic];
            
            model.yuanliao = [self yuanliao:model.yuanliao];
            
            // 添加到数组中
            [weakSelf.cookListArray addObject:model];
   
        }
        
        block();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"fail:%@",error);
        
    }];
    
}


// 懒加载
- (NSMutableArray *)cookListArray
{
    if (!_cookListArray) {
        
        _cookListArray = [NSMutableArray array];
        
    }
    
    return _cookListArray;
}



// 返回数组个数
- (NSInteger)countOfCookListArray
{
    return self.cookListArray.count;
}



// 返回数组下标
- (Model *)returnModelWithIndex:(NSInteger)index
{
    return self.cookListArray[index];
}


//原料数据处理
- (NSString *)yuanliao:(NSString *)yuanliao
{
    NSArray *array = [yuanliao componentsSeparatedByString:@"</span>"];
    NSMutableString  *string = [NSMutableString string];
    
    for (NSString *string1 in array) {
        
        NSArray *array2 = [NSArray array];
        if (array.count == 1) {
            return string1;
        }else
        {
            array2 = [string1 componentsSeparatedByString:@"<span>"];
            
            
        }
        if (array2.count != 1) {
            [string appendString:array2[0]];
            [string appendString:array2[1]];
        }
    }
    

    
    return string;

}




@end
